package com.ruoyi.web.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.domain.SearchToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

// 查询页面Token 管理
@RestController
@RequestMapping("/admin/token")
public class SearchTokenController extends BaseController {

    public static final String TOKEN_KEY = "search_token";
    @Autowired
    private RedisCache redisCache;

//    设置Token
    @PostMapping("/setToken")
    public AjaxResult setToken(@RequestBody SearchToken searchToken) {

        if (searchToken.getDay()==0){
            redisCache.setCacheObject(TOKEN_KEY,searchToken.getToken());
        }else {
            redisCache.setCacheObject(TOKEN_KEY,searchToken.getToken(),searchToken.getDay(), TimeUnit.DAYS);
        }

        return success("设置成功");
    }


//    查询Token

    @GetMapping("/getToken")
    public  AjaxResult getToken(){

        String searchToken = redisCache.getCacheObject(TOKEN_KEY);
        long expire = redisCache.getExpire(TOKEN_KEY);
        String date = getDate((int)expire);
        HashMap<String, String> map = new HashMap<>();
        map.put(TOKEN_KEY,searchToken);
        map.put("expire",date);
        return success(map);
    }


//    删除Token

    @PostMapping("/deleteToken")
    public  AjaxResult deleteToken(){

        redisCache.deleteObject(TOKEN_KEY);
        return success("删除成功");
    }

    public static String getDate(Integer date ) {
        if (date<60) {
            return date+"秒";
        }else if (date>60&&date<3600) {
            int m = date/60;
            int s = date%60;
            return m+"分"+s+"秒";
        }else {
            int h = date/3600;
            int m = (date%3600)/60;
            int s = (date%3600)%60;
            return h+"小时"+m+"分"+s+"秒";
        }

    }
}
